package cn.dulian.preparedstatement.crud;

import cn.dulian.bean.Customer;
import cn.dulian.util.JDBCUtils;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;

/**
 * @author dulian
 * @Description 针对于Customers表的查询操作
 * @create 2022-04-05 10:45
 */
public class CustomerForQuery {
    @Test
    public void testQueryForCustomers() {
        String sql = "SELECT id,name , birth,  email  FROM customers WHERE id =?";
        Customer customer = queryForCustomers(sql, 13);
        System.out.println(customer);

        sql = "SELECT name,email FROM customers WHERE name=?";
        Customer customer1 = queryForCustomers(sql, "周杰伦");
        System.out.println(customer1);

    }

    /**
     * @param sql
     * @param args
     * @return
     * @Description 针对于customers表的通用的查询操作
     */
    private Customer queryForCustomers(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            rs = ps.executeQuery();
            //获取结果集
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            if (rs.next()) {
                Customer cust = new Customer();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);
                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    //反射
                    Field field = Customer.class.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(cust, columnValue);
                }
                return cust;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }
        return null;

    }
}
